﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Runtime.InteropServices;

namespace MediaLibraryManager
{
	public partial class Video : IMyMoviesXmlExportable
	{
		[DllImport("kernel32.dll")]
		static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

		public static Video GetVideo(MediaLibraryDataContext db, Guid VideoFileID)
		{
			return db.Videos.SingleOrDefault(v => v.VideoFileID == VideoFileID);
		}

		/// <summary>
		/// Generates the file system structure used for MyMovies, MediaBrowser and other media center
		/// plug-ins by using symbolic links.
		/// </summary>
		/// <param name="path">The path of the folder where to start the structure.</param>
		public void GenerateMyMoviesFileSystemStructure(string path)
		{
			string name = this.VideoFile.FilePath.Split('\\').Last();
			name = name.Remove(name.Length - this.VideoFile.FileType.Length -1);

			string folder = String.Format("{0}{1}{2}",
								path,
								path.EndsWith(@"\") ? string.Empty : @"\",
								name);

			//Create the folder with the name of the video
			if (!Directory.Exists(folder))
				Directory.CreateDirectory(folder);

			//Create the symbolic link to the video file
			if (!File.Exists(
					String.Format(@"{0}\{1}.{2}",
						folder,
						name,
						this.VideoFile.FileType)))
			{
				CreateSymbolicLink(
					String.Format(@"{0}\{1}.{2}",
						folder,
						name,
						this.VideoFile.FileType),
					this.VideoFile.FilePath,
					0);
			}

			//Create the symbolic link to the thumbnail file
			if (!File.Exists(
					String.Format(@"{0}\folder.jpg",
						folder)))
			{
				CreateSymbolicLink(
					String.Format(@"{0}\folder.jpg",
						folder),
					String.Format(@"{0}.jpg",
						this.VideoFile.FilePath.Remove(this.VideoFile.FilePath.Length - this.VideoFile.FileType.Length - 1)),
					0);
			}

			//Generate the XML file with the video's data
			GenerateMyMoviesXml(
				String.Format(@"{0}\mymovies.xml",
						folder));
		}

		public void DeleteMyMoviesFileSystemStructure(string path)
		{
			string name = this.VideoFile.FilePath.Split('\\').Last();
			name = name.Remove(name.Length - this.VideoFile.FileType.Length - 1);

			string folder = String.Format("{0}{1}{2}",
								path,
								path.EndsWith(@"\") ? string.Empty : @"\",
								name);

			//Delete the folder with the name of the video
			if (Directory.Exists(folder))
				Directory.Delete(folder,true);
		}

		public void GenerateMyMoviesXml(string xmlFilePath)
		{
			XDocument doc = new XDocument(
					new XElement("Title",
						new XElement("LocalTitle", this.Song.Name),
						new XElement("OriginalTitle", this.Song.Name),
						new XElement("SortTitle", this.Song.Name),
						new XElement("Added", String.Format("{0:G}", this.VideoFile.DateAdded)),
						new XElement("ProductionYear", this.VideoFile.DateAdded.Year),
						new XElement("RunningTime", String.Format("{0:F2}",
							this.VideoFile.VideoLength == null ? 0 : this.VideoFile.VideoLength.Value.TotalMinutes)),
						new XElement("IMDBRating", String.Format("{0:F1}", 
							this.UserRating == null ? 
								(this.CalculatedRating == null ? 0 : this.CalculatedRating / 10) : this.UserRating / 10)),
						new XElement("Persons")
					)
				);

			XElement persons = doc.Descendants("Persons").ElementAt(0);

			foreach (Video_Artist item in this.Video_Artists.OrderBy(o => o.ItemOrder))
			{
				persons.Add(
						new XElement("Person",
							new XElement("Name", item.Artist.Name),
							new XElement("Type", "Actor")
						)
					);
			}

			doc.Save(xmlFilePath);
		}
	}
}
